import { Form, Input, Space, Button, Link, Checkbox, Message, Typography } from '@arco-design/web-react'
import useLocale from '@/hooks/useLocale.ts'
import locale from './locale'
import styles from './style/index.module.less'
import { useState } from 'react'
import useStorage from '@/hooks/useStorage'
import { post } from '@/utils/request'
import { useNavigate } from 'react-router'

const FormItem = Form.Item

const { Title } = Typography
const LoginForm = () => {
  const navigator = useNavigate()
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [loginParams, setLoginParams, removeLoginParams] = useStorage('loginParams')
  const t = useLocale(locale)
  const [rememberPassword, setRememberPassword] = useState(!!loginParams)

  type LoginParams = {
    username: string
    password: string
  }
  const afterLoginSuccess = (params: LoginParams, token: string) => {
    setLoading(false)
    // 记住密码
    if (rememberPassword) {
      setLoginParams(JSON.stringify(params))
    } else {
      removeLoginParams()
    }
    // 记录登录状态
    localStorage.setItem('token', token)
  }
  const login = (params: LoginParams) => {
    setLoading(true)
    post('/api/v1/auth/signin', params)
      .then((data) => {
        Message.success('登录成功')
        afterLoginSuccess(params, (data as any).access_token || '')
        navigator('/')
      })
      .finally(() => {
        setLoading(false)
      })
  }
  function onSubmitClick() {
    form
      .validate()
      .then((v) => {
        login(v)
      })
      .catch((e) => {
        console.log(e.errors)
      })
  }
  return (
    <div>
      <Title heading={2} style={{ fontSize: '20px' }}>
        {t['login.form.title']}
      </Title>
      <Form form={form} style={{ width: 320 }} wrapperCol={{ span: 24 }} autoComplete="off">
        <FormItem field="username" rules={[{ required: true, message: t['login.form.userName.errMsg'] }]}>
          <Input placeholder={t['login.form.userName.placeholder']} />
        </FormItem>
        <FormItem field="password" rules={[{ required: true, message: t['login.form.password.errMsg'] }]}>
          <Input placeholder={t['login.form.password.placeholder']} onKeyDown={(e) => e.key === 'Enter' && onSubmitClick()} />
        </FormItem>
        <Space size={16} direction="vertical">
          <div className={styles['login-form-password-actions']}>
            <Checkbox checked={rememberPassword} onChange={setRememberPassword}>
              {t['login.form.rememberPassword']}
            </Checkbox>
            <Link>{t['login.form.forgetPassword']}</Link>
          </div>
          <Button type="primary" long onClick={onSubmitClick} loading={loading}>
            {t['login.form.login']}
          </Button>
          <Button type="text" long className={styles['login-form-register-btn']}>
            {t['login.form.register']}
          </Button>
        </Space>
      </Form>
    </div>
  )
}
export default LoginForm
